import logging
import constants
import text
from World import string, projectile, world_object

class World(object):
    """Understands the world in which the character is evolving"""

    def __init__(self):
        self._objects = []
        self.log = logging.getLogger(constants.LOGGER_NAME)
    
    def add_object(self, world_obj):
        self._objects.append(world_obj)
    
    def objects(self):
        return self._objects

    def cleanup(self, screen_height=constants.SCREEN_HEIGHT):

        for obj in self._objects:
            obj.empty_collision_list()
            if obj.position()[1] > (screen_height + constants.BELOW_SCREEN_GRACE):
                if hasattr(obj, 'hit'): obj.hit()
                else: obj.die()

            if obj.is_dead():
                self.log.debug("removing from world: %s" % obj)
                self._objects.remove(obj)

    def sort_objects(self):
        self._objects.sort(cmp=world_object.WorldObject.cmp_z_index) 

    def contains(self, obj):
        return obj in self._objects
    
    def all_strings(self):
        return [str for str in self._objects if type(str) == string.String]

    def all_projectiles(self):
        return [proj for proj in self._objects if type(proj) == projectile.Projectile]
    
    def update_sprites(self):
        for obj in self._objects:
            obj.update()
    
    def empty(self):
        for obj in self._objects: obj.die()
    
    def create_osd(self, hero):
        """Creates some text to show the character status like number of lives"""
        self.add_object(text.Text("lives   x", x=5, y=5))

        lives_text = text.Text(str(constants.FULL_LIFE), x=95, y=5)
        score_text = text.Text("1", x=5, y=30)

        self.add_object(score_text)
        self.add_object(lives_text)

        old_tick_update = lives_text.tick_update
        def lives_text_tick_update():
            lives = hero.life().remaining()
            lives_text.update_surface(lives)
            old_tick_update()

        lives_text.tick_update = lives_text_tick_update

        old_tick_update = score_text.tick_update
        def score_text_tick_update():
            score = hero.points()
            score_text.update_surface(score)
            old_tick_update()

        score_text.tick_update = score_text_tick_update

